package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {

//        // 使用互斥锁查询 解决缓存击穿
//        Shop shop = queryWithMutex(id);
        // 使用逻辑过期 解决缓存击穿
        Shop shop = queryExpireLogic(id);
        if (shop == null) {
            return Result.fail("店铺id不存在");
        }

        return Result.ok(shop);
    }
    private static  final ExecutorService  CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop queryExpireLogic(Long id) {
        // 查询redis中是否存在
         String shopStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 判断是否存在redis缓存中
        // 不存在 直接返回
        if (StringUtil.isBlank(shopStr)) {
            return null;
        }
        // 存在 判断缓存是否过期
        RedisData bean = JSONUtil.toBean(shopStr, RedisData.class);
        JSONObject jsonObject = (JSONObject)bean.getData();
        Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
        LocalDateTime expireTime = bean.getExpireTime();
        // 没过期 返回店铺数据
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }
        // 过期
        // 获取锁的状态
        if (createLock(id)) {
            // 成功 开启新线程 查询并加入到缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    saveKey(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    deleteLock(id);
                }
            });
        }
        // 未成功 返回过期数据
        return shop;
    }


    // 保存逻辑过期key到redis缓存中
    public void saveKey(Long id, Long expireSeconds) throws InterruptedException {
        // 根据id获取key
        Shop shop = getById(id);
        Thread.sleep(200);
        // 设置key保存redis中
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 保存数据到redis中
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    public Shop queryWithMutex(Long id) {
        // 查询redis中是否存在
        String shopStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        if (StringUtil.isNotBlank(shopStr)) {
            // 存在 直接返回
            // 将字符串转换为对象
            Shop shop = JSONUtil.toBean(shopStr, Shop.class);
            return shop;
        }

        if (shopStr != null) {
            return null;
        }

        Shop shop = null;

        try {

            // 获取互斥锁
            if (!createLock(id)) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // 缓存不存在 去数据库查询
            shop = getById(id);

            Thread.sleep(200);

            // 数据库不存在 返回错误信息
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            // 数据库存在 把数据保存到缓存中并返回
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            deleteLock(id);
        }
        return shop;
    }
    
    // 设置互斥锁
    private boolean createLock(Long id){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_SHOP_KEY + id, "1", LOCK_SHOP_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(b);
    }
    // 删除互斥锁
    private void deleteLock(Long id){
        stringRedisTemplate.delete(LOCK_SHOP_KEY + id);
    }

    // redis穿透处理 储存空null
    public Result queryById1(Long id) {
        // 查询redis中是否存在
        String shopStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        if (StringUtil.isNotBlank(shopStr)) {
            // 存在 直接返回
            // 将字符串转换为对象
            Shop shop = JSONUtil.toBean(shopStr, Shop.class);
            return Result.ok(shop);
        }

        if (shopStr != null) {
            return Result.fail("商品id不存在!");
        }


        // 不存在 去数据库查询
        Shop shop = getById(id);

        // 不存在 返回错误信息
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.ok("商品id不存在!");
        }

        // 存在 把数据保存到缓存中并返回
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不存在!");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok() ;
    }
}
